# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor
from utils.alerts.doris_telnet_check import net_is_used
from airflow.exceptions import AirflowSkipException
import pendulum

cst = pendulum.timezone('Asia/Shanghai')

class WeekRichSqlSensor(RichSqlSensor):

    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)

        days_of_week = ['1']

        if day.strftime('%w') not in days_of_week:
            print(f'{day.strftime("%w")} not in {days_of_week}, should skip')
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%w")} in {days_of_week}, run now')
            super().pre_execute(context)

label = f"dwd_route_effective_slowest_w{int(time())}"
timeout = timedelta(minutes=30).seconds
dorisConn = net_is_used()

doris_jms_dwd__dwd_route_effective_slowest_w = WeekRichSqlSensor(
    task_id='doris_jms_dwd__dwd_route_effective_slowest_w',
    pool='broker_load_pool',
    email=['suning@jtexpress.com','yl_bigdata@yl-scm.com'],
    conn_id='new_doris',
    pre_sql=f"""
             LOAD LABEL jms_dwd.{label} (
                 DATA INFILE('hdfs://yl-bg-hdp/dw/hive/jms_dm.db/external/dm_slowest_route_area_effective_w/wt={{{{ execution_date | date_add(0) | year_week }}}}/*')
                 INTO TABLE dwd_slowest_route_area_effective_w
                 FORMAT AS 'PARQUET'
             )
             WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
             PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dwd WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dwd WHERE LABEL = '{label}'",
    success=lambda r: (r[2] == 'FINISHED'),
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    #execution_timeout=timedelta(seconds=timeout + 120)
    #excel平均时长:2分3秒
    execution_timeout = timedelta(minutes=30), )

print(label)

